package mani.multithreading;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

public class TestCPUUsageByThread {

	private List<Map.Entry<Long, ThreadInfo>> getThreadList() {

		ThreadMXBean tmbean = ManagementFactory.getThreadMXBean();
		long[] tids = tmbean.getAllThreadIds();
		ThreadInfo[] tinfos = tmbean.getThreadInfo(tids);

		// build a map with key = CPU time and value = ThreadInfo
		SortedMap<Long, ThreadInfo> map = new TreeMap<Long, ThreadInfo>();
		for (int i = 0; i < tids.length; i++) {
			long cpuTime = tmbean.getThreadCpuTime(tids[i]);
			// filter out threads that have been terminated
			if (cpuTime != -1 && tinfos[i] != null) {
				map.put(new Long(cpuTime), tinfos[i]);
			}
		}

		Set<Map.Entry<Long, ThreadInfo>> set = map.entrySet();
		List<Map.Entry<Long, ThreadInfo>> list = new ArrayList<Map.Entry<Long, ThreadInfo>>(
				set);
		Collections.reverse(list);
		return list;
	}

	public static void main(String args[]) {
		TestCPUUsageByThread Obj = new TestCPUUsageByThread();
		List<Map.Entry<Long, ThreadInfo>> obj = Obj.getThreadList();
		int size = obj.size();
		for (int i = 0; i < size; i++) {
			System.out.println(obj.get(i).getValue().getThreadName() + " "
					+ obj.get(i).getKey());
		}
	}
}
